﻿using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Timers;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using LiveChartsCore.SkiaSharpView;
using ui_test.ViewModels;

namespace ui.test.Views;

public partial class UserControl2 : UserControl
{
    public UserControl2()
    {
        DataContext = new UserControl2ViewModel();
        InitializeComponent();
    }

    public static class NativeMethods
    {
        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    }

    public static string? GetForegroundWindowTitle()
    {
        const int nChars = 256;
        IntPtr handle = NativeMethods.GetForegroundWindow();
        if (handle == IntPtr.Zero)
        {
            return null;
        }

        StringBuilder builder = new(nChars);
        if (NativeMethods.GetWindowText(handle, builder, nChars) > 0)
        {
            return builder.ToString();
        }

        return null;
    }

    protected override void OnLoaded(RoutedEventArgs e)
    {
        Console.WriteLine(899898998);
        base.OnLoaded(e);
        InitialHooks();
    }

    private static void InitialHooks()
    {
        // new Timer(state =>
        // {
        // }, null, 0, 1000);
        // Timer timer = new Timer((state =>
        // {
        //     
        // }), null, 0, 1000);
        var timer = new Timer(1000L);
        timer.Elapsed += ((sender, args) =>
        {
            var title = GetForegroundWindowTitle();
            Console.WriteLine($"current window is {title}");
        });
        timer.AutoReset = true;
        timer.Enabled = true;
        timer.Start();
    }
}